package appControl

import (
	"server/appControl/chat"
	"server/appControl/user"
	"server/proto"
	"server/public"
)

/*
*  -*- coding:utf8 -*-
*
*   处理客户端发过来的相关请求
*
*  @Author  : chengms
*  @WebSite : chengms.com
*  @Email   : chengms2012@163.com
*  @TIME    : 2020/8/20 16:39
*  @File    : handler.go
 */

func HandlerLongin(cc *proto.ClientConn, data []string) (err error) {
	var userOp user.UserOption

	err = public.Jsonit.UnmarshalFromString(data[0], &userOp.Info)
	if err != nil {
		public.Loggerf.Error(err)
	}

	//cc.Writer.
	resp := user.UserOpSts{}

	cc.UserName = userOp.Info.UserName
	resp.UserStatus, err = userOp.UserLogin()
	if err != nil {
		public.Loggerf.Infof("Login fail!")
		resp.Msg = "Login Failed"
	}
	cc.UserId = userOp.Info.UserId
	resp.UserId = cc.UserId
	resp.Msg = "Login successfully"

	// send msg to client
	CmdBuf := proto.NewSendCommand(proto.CmdLogin)
	err = cc.SendMsg(CmdBuf, resp)
	if err != nil {
		public.Loggerf.Error(err)
	}
	return
}

func HandlerRegister(cc *proto.ClientConn, data []string) (err error) {
	var userOp user.UserOption
	public.Loggerf.Info(data[0])
	err = public.Jsonit.UnmarshalFromString(data[0], &userOp.Info)
	if err != nil {
		public.Loggerf.Error(err)
	}
	//cc.Writer.
	resp := user.UserOpSts{}

	cc.UserName = userOp.Info.UserName
	resp.UserStatus, err = userOp.UserRegister()
	if err != nil {
		public.Loggerf.Infof("Register fail!")
		resp.Msg = "Register Fail"
	}
	cc.UserId = userOp.Info.UserId

	resp.UserId = cc.UserId
	resp.Msg = "Register successfully"

	// send msg to client
	CmdBuf := proto.NewSendCommand(proto.CmdRegister)
	err = cc.SendMsg(CmdBuf, resp)
	if err != nil {
		public.Loggerf.Error(err)
	}

	return
}

func HandlerHearbeat(cc *proto.ClientConn) {
	public.Loggerf.Debugf("Recv hearbeat from: %d %s", cc.UserId, cc.UserName)

}

func HandlerSendChat(cc *proto.ClientConn, data []string) (err error) {
	var chatbuf chat.ChatMsg
	err = public.Jsonit.UnmarshalFromString(data[0], &chatbuf)
	if err != nil {
		public.Loggerf.Error(err)
	}

	return
}

func HandlerGroupChat(cc *proto.ClientConn, data []string) (err error) {

	return
}
